linux expect ssh自动登录详解

简介

Expect是用于自动化交互式应用程序的工具,如telnet,ftp,passwd,fsck,rlogin,tip等。使用起来很简单。

使用方法

  1. 首行加上/usr/bin/expect
  2. spawn: 后面加上需要执行的shell 命令,比如说spawn sudo touch testfile
  3. expect: 只有spawn 执行的命令结果才会被expect 捕捉到,因为spawn 会启
    动一个进程,只有这个进程的相关信息才会被捕捉到,主要包括:标准输入的提
    示信息,eof 和timeout。
  4. send 和send_user:send 会将expect 脚本中需要的信息发送给spawn 启动
    的那个进程,而send_user 只是回显用户发出的信息,类似于shell 中的echo 而
    已。

实例

1:远程拷贝文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
set timeout 10
set host [lindex $argv 0]
set username [lindex $argv 1]
set password [lindex $argv 2]
set src_file [lindex $argv 3]
set dest_file [lindex $argv 4]
spawn scp $src_file $username@$host:$dest_file
expect {
"(yes/no)?"
{
send "yes\n"
expect "*assword:" { send "$password\n"}
}
"*assword:"
{
send "$password\n"
}
}
expect "100%"
expect eof

2:执行远程命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
set timeout 10
set host [lindex $argv 0]
set username [lindex $argv 1]
set password [lindex $argv 2]
set cmd [lindex $argv 3]

spawn ssh -t -p $port $username@$host 'cmd'
expect {
"(yes/no)?"
{
send "yes\n"
expect "*assword:" { send "$password\n"}
}
"*assword:"
{
send "$password\n"
}
}
expect "100%"
expect eof

3:与SSH合用

1
2
3
/usr/bin/expect <<-EOF
//TODO这里写expect脚本
EOF